import re

from rest_framework import serializers, mixins, viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response

import logging

from busness_manage.settings import QINIU_TOKEN
from tools.redis_tools.redis_server import redis_client
from user_info.models import UserInfo, Information
from user_info.serializers import UserInfoSerializer, InformationSerializer
from utils.common.common import md5
from utils.common.token import generate_token

logger = logging.getLogger('django')


class UserInfoViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                      mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = UserInfo.objects.filter(is_delete=False).all()
    serializer_class = UserInfoSerializer

    def create(self, request, *args, **kwargs):
        """
        创建新用户
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        request.data['password'] = md5('20yumei22')
        username = request.data['username']
        if not (5 < len(username) < 13 and username.isalpha()):
            raise serializers.ValidationError('账号长度必须是6-12位字母')
        result = super().create(request)
        return Response(result.data)

    @list_route(['POST'])
    def login(self, request):
        """后台用户登录"""
        params = request.data
        username = params.get('username')
        password = params.get('password')
        if not all((username, password)):
            raise serializers.ValidationError('用户名和密码不能为空')
        result = UserInfo.objects.filter(username=username, password=password, is_delete=False).values().first()

        # 用户名密码校验成功之后生成token放到请求头中返回
        if result:
            token_data = generate_token(result['id'])
            redis_client.set_instance(str(result['id']) + '_0', token_data)
            response = Response(
                {'user_id': result['id'], 'user_name': result['username'], 'create_time': result['create_time'],
                 'qiniu_token': QINIU_TOKEN})
            response.setdefault('token', token_data)
            response['Access-Control-Expose-Headers'] = 'token'
            return response
        else:
            raise serializers.ValidationError('用户名或密码验证失败')

    @list_route(['GET'])
    def reset_password(self, request):
        """
        重置用户密码
        :param request:
        :return:
        """
        params = request.query_params
        user_id = params.get('user_id')
        if not user_id:
            raise serializers.ValidationError('user_id为空')
        UserInfo.objects.filter(id=user_id).update(password=md5('20yumei22'))
        return Response('重置密码成功')

    @list_route(['POST'])
    def modify_password(self, request):
        """
        修改密码
        :param request:
        :return:
        """
        old_pwd = request.data.get('old_pwd')
        new_pwd = request.data.get('new_pwd')
        confirm_pwd = request.data.get('confirm_pwd')
        if new_pwd != confirm_pwd:
            raise serializers.ValidationError('新密码两次输入不一致')
        if not all([old_pwd, new_pwd, confirm_pwd]):
            raise serializers.ValidationError('修改密码参数不足')
        user = request.user
        if md5(old_pwd) != user.password:
            raise serializers.ValidationError('原密码输入错误')
        if not (bool(re.search(r'\d', new_pwd)) and bool(re.search(r'[A-Za-z]', new_pwd)) and len(new_pwd) > 5):
            raise serializers.ValidationError('密码长度至少6位，必须包含数字字母')
        user.password = md5(confirm_pwd)
        user.save()
        return Response('修改密码成功')


class InformationViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                         mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = Information.objects.all()
    serializer_class = InformationSerializer

    @list_route(['GET'])
    def get_all(self, request):
        """获取所有轮播图"""
        return Response(self.queryset.values())